<template>
  <div class="login-container">
    <!-- 右侧登录注册容器 -->
    <div class="login-end-container">
      <!-- 组件容器 -->
      <div class="login_end_module">
        <!-- 介绍语句 -->
        <div class="introduce">
          <div class="title">
            <p class="text">欢迎注册知识渔用户</p>
            <p class="solid"></p>
          </div>
          <div class="subtitle">按步骤填写信息完成注册流程</div>
        </div>
        <!-- 输入框区域 -->
        <div class="input_area">
          <el-form ref="customForm" :rules="rules" :model="ruleForm">
            <el-form-item label="" prop="nickname">
              <span class="">用户名</span>
              <el-input v-model="ruleForm.nickname"></el-input>
            </el-form-item>
            <el-form-item label="" prop="password">
              <span class="">密码</span>
              <el-input
                v-model="ruleForm.password"
                type="password"
                style="padding-right: 20px"
                v-show="!toggle.showWord"
              ></el-input>
              <el-input
                v-show="toggle.showWord"
                v-model="ruleForm.password"
                type="input"
                style="padding-right: 20px"
              ></el-input>
              <div class="operation" style="text-align: right">
                <a href="javascript:;">
                  <i
                    @click="toggleModule"
                    class="iconfont"
                    :class="toggle.showWord ? 'icon-yanjing' : 'icon-yanjing1'"
                  ></i>
                </a>
              </div>
            </el-form-item>
            <el-form-item label="" prop="email" ref="emailElem">
              <span class="">邮箱</span>
              <el-input
                v-model="ruleForm.email"
                type="email"
                style="padding-right: 20px"
              ></el-input>
              <div class="operation" style="width: 100px">
                <a
                  href="javascript:;"
                  @click="sendEmailCode"
                  ref="selfCode"
                  :style="
                    toggle.sendCode
                      ? 'color: #999; cursor: not-allowed !important;'
                      : ''
                  "
                  >{{ toggle.sendCode ? toggle.time : "发送验证码" }}</a
                >
              </div>
            </el-form-item>
            <el-form-item label="" prop="code">
              <span>验证码</span>
              <el-input v-model="ruleForm.code"></el-input>
            </el-form-item>
            <el-form-item label="" prop="userTcp" ref="tcp">
              <el-checkbox v-model="ruleForm.userTcp">
                <span class="tcp">
                  我已阅读并同意<a href="javascript:;">《服务协议》</a>和<a
                    href="javascript:;"
                    >《知识渔隐私政策》</a
                  >
                </span>
              </el-checkbox>
            </el-form-item>
          </el-form>
        </div>
        <!-- 确定提交 -->
        <div class="submit">
          <el-button
            type="primary"
            :loading="registerLoading"
            @click="register('customForm')"
            >立即注册</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { uuid } from "@/utils/uuid";
import { throttle } from "lodash";
import dayjs from "dayjs";
import { Loading } from "element-ui";
import {
  username_validator,
  password_validator,
  email_validator,
  userTcp_validator,
  code_validator,
} from "@/utils/validate";

export default {
  name: "UserRegister",
  data() {
    return {
      // 切换合集
      toggle: {
        // 切换密码显示
        showWord: false,
        // 发送验证码
        sendCode: false,
        // 用于倒计时的验证码
        time: 59,
        // 倒计时的定时器
        timer: null,
      },
      // 校验图片路径和描述信息
      ruleForm: {
        // 用户名
        nickname: "",
        // 密码
        password: "",
        // 邮箱
        email: "",
        // 验证码
        code: "",
        // 是否勾选协议
        userTcp: false,
      },
      rules: {
        // 用户名
        nickname: [
          {
            validator: username_validator,
            trigger: "blur",
            required: true,
          },
        ],
        // 密码
        password: [
          {
            validator: password_validator,
            trigger: "blur",
            required: true,
          },
        ],
        // 邮箱
        email: [
          {
            validator: email_validator,
            trigger: "blur",
            required: true,
          },
        ],
        // 验证码
        code: [
          {
            validator: code_validator,
            trigger: "blur",
            required: true,
          },
        ],
        // 用户协议
        userTcp: [
          {
            validator: userTcp_validator,
            trigger: "blur",
            required: true,
          },
        ],
      },
      // 服务loading
      loadingInstance: null,
      // 注册的loading
      registerLoading: false,
    };
  },
  methods: {
    // 切换密码明文显示
    toggleModule() {
      this.toggle.showWord = !this.toggle.showWord;
    },
    // 发送验证码，节流处理
    sendEmailCode: throttle(function () {
      if (!this.ruleForm.email.trim())
        return this.$win("请先填写邮箱 😅", "error");
      // 发送了验证码后不能继续发送
      if (this.toggle.sendCode) return;
      // 开始转圈提醒用户，正在发送中
      this.loadingInstance = Loading.service({
        target: this.$refs.selfCode,
        spinner: "el-icon-loading",
      });
      // 发送验证码
      this.$api
        .sendCode(this.ruleForm.email)
        .then((res) => {
          // 以服务的方式调用的 Loading 需要异步关闭
          this.$nextTick(() => {
            this.loadingInstance.close();
          });
          if (res.code === 200) {
            this.toggle.sendCode = true;
            // 开启定时器
            this.toggle.timer = setInterval(() => {
              this.toggle.time--;
              if (this.toggle.time <= 0) {
                clearInterval(this.toggle.timer);
                this.toggle.sendCode = false;
                this.toggle.time = 59;
              }
            }, 1000);
          }
        })
        .catch(() => {
          // 以服务的方式调用的 Loading 需要异步关闭
          this.$nextTick(() => {
            this.loadingInstance.close();
          });
        });
    }, 2000),
    // 立即注册
    register: throttle(function (formName) {
      // 已发布状态代码
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.registerLoading) return;
          // 开启注册loading状态
          this.registerLoading = true;
          // 取出属性值
          let { nickname, password, email, code } = this.ruleForm;
          let uid = uuid();
          // 拼接data参数
          const data = {
            selfStr: `${uid[0]}${uid[1]}${nickname[0]}`,
            userName: nickname,
            nickName: nickname,
            password,
            email,
            code,
            user_id: uid,
            createTime: +dayjs(),
          };
          // 发送注册请求
          this.$api
            .register(data)
            .then((result) => {
              // 关闭注册loading状态
              this.registerLoading = false;
              if (result.code === 200) {
                let options = {
                  userName: nickname,
                  password,
                  loginType: "account",
                };
                // 发送请求
                this.$store.dispatch("user/Login", options).then(() => {
                  this.$win("注册成功");
                  this.$router.replace("/community/article");
                });
              }
            })
            .catch(() => {
              // 关闭注册loading状态
              this.registerLoading = false;
            });
        } else {
          return false;
        }
      });
    }, 2000),
    // 初始化事件
    _initEvent() {
      // 实现渐入渐出
      document
        .querySelectorAll(".login-container .el-form-item__content")
        .forEach((item) => {
          // 给每一个绑定获得焦点事件
          const elem = item.querySelectorAll(".el-input__inner");
          /**
           * 循环两次解决切换明文密码切换时，让input节点发生了改变，导致focus和blur事件失效问题
           */
          elem.forEach((item2) => {
            if (item2 === null) return;
            const span = item.querySelector("span");
            item2.onfocus = function () {
              span.classList.add("letter_active");
            };
            item2.onblur = function () {
              if (this.value.trim() !== "") return;
              span.classList.remove("letter_active");
            };
          });
        });
      // 给协议绑定点击事件
      const checkbox = document.querySelector(
        ".login-container .el-checkbox__input"
      );
      checkbox.onclick = () => {
        this.$refs.tcp.clearValidate();
      };
    },
  },
  mounted() {
    this._initEvent();
  },
};
</script>

<style lang="less" scoped>
.login-container {
  height: calc(100vh - 64px);
  background: #f0f2f5;
  background-image: url("@/assets/images/login/bg.svg");
  background-repeat: no-repeat;
  background-position: center 110px;
  background-size: 100%;
  /* 水平垂直居中 */
  display: flex;
  align-items: center;
  justify-content: center;
  /deep/.el-form-item__error {
    padding-top: 8px;
  }
  // 右侧登录注册容器
  .login-end-container {
    margin-top: -80px;
    .login_end_module {
      /* 水平垂直居中 */
      width: 500px;
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgb(0 0 0 / 8%), 0 0 1px rgb(1 0 0 / 10%);
      padding: 50px;
      .introduce {
        text-align: left;
        margin-bottom: 60px;
        .title {
          position: relative;
          height: 45px;
          margin-bottom: 8px;
          & > p {
            margin-bottom: 0;
          }
          .text {
            font-size: 30px;
            position: absolute;
            font-weight: 700;
            z-index: 2;
          }
          .solid {
            max-width: 270px;
            position: absolute;
            left: 0;
            bottom: 4px;
            background: #f2f2f2;
            height: 12px;
            width: 100%;
          }
        }
        .subtitle {
          color: #999;
          font-size: 14px;
        }
      }
      .submit {
        margin-top: 40px;
        width: 100%;
        button {
          height: 38px;
          font-size: 14px;
          width: 100% !important;
        }
      }
    }
  }
  // 调整输入框
  /deep/.el-form-item:nth-of-type(4) .el-form-item__content {
    margin-bottom: -6px !important;
  }
  /deep/.el-form-item:nth-of-type(5) .el-form-item__content {
    border-bottom: 0 !important;
    margin-bottom: 0;
    a {
      color: #359eff;
      &:hover {
        color: #359eff !important;
      }
    }
  }
  /deep/.el-form-item__content {
    display: flex;
    position: relative;
    margin-bottom: 20px;
    border-radius: 0;
    border-bottom: 3px solid #e1e1e1 !important;
    & > span {
      position: absolute;
      z-index: 0;
      /* 水平垂直居中 */
      position: absolute;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
      font-size: 18px;
      transition: font 0.3s, top 0.3s, transform 0.3s;
      color: #999;
    }
    .el-input {
      height: 42px;
      input {
        font-size: 16px;
        background: #ffffff00;
        padding: 0 !important;
        height: 100%;
        border: 0;
      }
    }
    .el-checkbox {
      cursor: url("@/assets/mouse/x1.cur"), auto !important;
      .el-checkbox__input {
        cursor: url("@/assets/mouse/x2.cur"), auto !important;
      }
      .el-checkbox__label {
        .tcp {
          color: #999;
          a {
            transition: color 0.4s;
            &:hover {
              color: var(--a-button-hover-color);
            }
          }
        }
      }
    }
    .operation {
      padding-right: 10px;
      text-align: right;
      line-height: 42px;
      .el-loading-spinner {
        right: -50px;
        width: 120px;
        top: 52%;
        background-color: #fff;
      }
      .el-icon-loading {
        font-size: 18px;
      }
      // 出现浮入效果
      a {
        transition: color 0.4s;
        &:hover {
          color: var(--a-button-hover-color);
        }
      }
    }
  }
  // 输入框汉字上调样式类名
  .letter_active {
    font-size: 14px !important;
    top: -30px !important;
    transform: translateY(0) !important;
  }
}
</style>